package com.lixl.threadpool;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;


/**
 * 多个线程共享变量的例子<br>
 * 多个线程要读写同一个变量，必须进入同步块，即某个时间点只能有一个线程读或者写该变量，否则会混乱；
 * @author Administrator
 *
 */
public class ShareVarDemo {

	private static int sum = 0;
	private static List<Task> list = new ArrayList<ShareVarDemo.Task>();
	
	public static ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(10);
	
	public static void main(String[] args) {
		
		for (int i = 0; i < 10; i++) {
			Task task = new ShareVarDemo.Task();
			list.add(task);
			task.start();
		}
		
		while(true){
			
			if(isAllDead()){
				
				System.out.println(sum()+"\t"+sum);
				break;
			}
			
		}
		
	}
	
	private static int sum(){
		int sum=0;
		for (int r:queue) {
			sum +=r;
		}
		
		return sum;
	}
	
	private static boolean isAllDead(){
		boolean allDead = true;
		for(Task task:list){
			allDead = allDead&&(!task.isAlive());
		}
		return allDead;
	}
	
	static class Task extends Thread{
		
		@Override
		public void run() {
			synchronized (this) {
				int a = (int)(new Random().nextDouble()*20);
				queue.add(a);
				System.out.println(this.getName()+"\t"+a);
				sum += a;
				//System.out.println("sum = "+sum);
			}
		}
		
	}

}
